package com.gao.security.autoconfig.verificationcode.filter;

import com.gao.security.autoconfig.verificationcode.properties.RegisterUrlService;
import com.gao.security.verificationcode.web.verificate.VerificationCodeManager;
import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-08-05 15:16
 */
public class SendValidateCodeAuthenticationFilter extends OncePerRequestFilter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private List<RequestMatcher> requestMatchers = Lists.newArrayList();

    private VerificationCodeManager manager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if(!requiresAuthentication(request)){
            filterChain.doFilter(request,response);
            return;
        }
        manager.send(request,response);
    }

    private boolean requiresAuthentication(HttpServletRequest request) {

        return requestMatchers.stream().anyMatch(requestMatcher -> requestMatcher.matches(request));

    }

    @Override
    public void afterPropertiesSet() throws ServletException {
        List<String> sendUrl = applicationContext.getBean(RegisterUrlService.class).getSendUrl();
        this.requestMatchers= sendUrl.stream()
                .map(s -> new AntPathRequestMatcher(s, "POST"))
                .collect(Collectors.toList());

        this.manager= applicationContext.getBean(VerificationCodeManager.class);
        super.afterPropertiesSet();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }



}
